package by.ad.appengine;

import java.util.Calendar;
import com.google.appengine.api.datastore.DatastoreTimeoutException;
import com.google.appengine.api.memcache.MemcacheService;
import com.google.appengine.api.memcache.MemcacheServiceFactory;
import com.google.appengine.api.utils.SystemProperty; 
import com.google.appengine.api.utils.SystemProperty.Environment;
import com.google.apphosting.api.ApiProxy.ApiDeadlineExceededException;

public abstract class Utils 
{
  // parameters and column names
  public static final String TIMESTAMP = "timestamp".intern();

  public static final boolean isProductionEnv =
    SystemProperty.environment.value() == Environment.Value.Production;
   
  public static final MemcacheService cache = MemcacheServiceFactory.getMemcacheService();
    
  // try to use datastore multiple times
  protected static void datastoreTrySeveralTimes(final Runnable task, 
    final long startTime, final long workTimeLimit) 
  {
    if ((Calendar.getInstance().getTimeInMillis() - startTime) < workTimeLimit) {
      try {
        task.run();
      } catch(ApiDeadlineExceededException e) {
        datastoreTrySeveralTimes(task, startTime, workTimeLimit); // next try
      } catch(DatastoreTimeoutException e) {
        datastoreTrySeveralTimes(task, startTime, workTimeLimit); // next try
      }
    } else {
      task.run(); // last try
    }
  }
  
  // try to use datastore up to 15 seconds
  public static void datastoreTrySeveralTimes(final Runnable task) {
    datastoreTrySeveralTimes(task, Calendar.getInstance().getTimeInMillis(), 15000);
  }
  
}
